import os
import sys
sys.path.append('../')
from utility.hdf5 import HDF5
import numpy as np
#import h5py
import random
import time
from pathlib import Path
from sgfmill import sgf,boards,ascii_boards
from utilities import *
from board_fast import Board,Game,Player,Point,Move


def list_all_file(fPath):
    fileList=os.listdir(fPath)
    file_list=[]
    for i in fileList:
        file_dir=Path(fPath+'/'+i)
        if file_dir.is_file():
            file_list.append(file_dir)
    return file_list


class sgf_parser:
    def __init__(self,filePath,h5file=None,mode='a'):
        with open(filePath,"rb") as f:
            self.game=sgf.Sgf_game.from_bytes(f.read())
        self.fileName=os.path.basename(filePath)
        self.winner=self.game.get_winner()
        self.boardsize=self.game.get_size()
        self.h5file=HDF5(h5file,mode=mode)
        self.board=Board(size=self.boardsize)

    def parse(self):
        for index,node in enumerate(self.game.get_main_sequence()):
            who,move=node.get_move()
            if who is not None and move is not None:
                if who=='b':
                    player=Player.black
                else:
                    player=Player.white
                planes=np.vstack((to_plane_color(self.board,player),to_ones(self.board),to_zeros(self.board),
                        to_legal_moves(self.board,player),turn_since(self.board,not_reset=index-1),
                        liberties(self.board),three_in_one(self.board,player))) #组合平面
                if self.h5file is not None:
                    self.saveSamples(str(index),planes,player,move)
                '''
                os.system('cls')
                for i in range(8):
                    print(planes[38+i])
                input("wait")
                '''
                point=Point(row=move[0]+1,col=move[1]+1)    #由于sgfmill的原点在左下角，且从0开始计数，生成的棋盘会是一个水平翻转，但是不影响
                self.board.play_stone(player,point)
        #os.system('cls')
        #input("now")
    def saveSamples(self,dsetName,planes,player,move):
        grpName=self.fileName
        if not self.h5file.isGrpExist(grpName):
            self.h5file.add_group(grpName)
            if self.winner=='b':
                winner=1
            else:
                winner=-1
            self.h5file.set_grp_attrs(grpName,'winner',winner) #如果第一次建，就设置该局的胜利方
            self.h5file.set_grp_attrs(grpName,'size',self.boardsize)    # 记录棋盘的大小
        self.h5file.add_dataset(grpName,dsetName,planes)
        if player==Player.black:
            nplayer=1
        else:
            nplayer=-1
        self.h5file.set_dset_attrs(grpName,dsetName,'player',nplayer)
        self.h5file.set_dset_attrs(grpName,dsetName,'move',move)


if __name__ == "__main__":
    doc='./sgfs/'
    h5file='./train_files/game_recorders.h5'
    file_lists=list_all_file(doc)
    since=time.time()
    for i in file_lists:
        #one_sgf=sgf_parser(i,h5file)
        #one_sgf.parse()
        #'''
        try:
            one_sgf=sgf_parser(i,h5file)
            one_sgf.parse()
            #one_sgf.showGame()
            #one_sgf.closeParser()
        except:
            print("error,filename:",i)
        else:
            None
        #'''
    print(time.time()-since)
